package cn.edu.seu.herald.informationplatform.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.LeagueInfo;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;

public class LeagueIntroduceEdit extends HttpServlet {
	
	private static final boolean SUCCESS = true;
	
	private static final boolean FAILURE = false;
	
	private static final String SUCCESS_MESSAGE = "操作成功";
	
	private static final String FAILURE_MESSAGE = "操作失败";
	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String introduction = request.getParameter("introduce");
		System.out.println(introduction);
		
		if (introduction == null) {
			printResult(response, FAILURE);
			return;
		}
		
		try {
			LeagueUserSessionCookieAccess luSessionCookieAccess =
					new LeagueUserSessionCookieAccess(request);
			int leagueId = luSessionCookieAccess.getLeagueId();
			LeagueInfoDao leagueInfoAccess = LeagueInfoDao.getDao();
			LeagueUserDao leagueUserDao = LeagueUserDao.getDao();
			LeagueUser leagueUser = leagueUserDao.getLeagueUser(leagueId);
			LeagueInfo previousLeagueInfo = leagueInfoAccess.getLeagueInfo(leagueUser.getLeagueInfoId());
			LeagueInfo leagueInfo = new LeagueInfo();
			leagueInfo.setIntroduction(introduction);
			leagueInfo.setName(previousLeagueInfo.getName());
			leagueInfo.setLastLoginTime(previousLeagueInfo.getLastLoginTime());
			leagueInfo.setRegisterTime(previousLeagueInfo.getRegisterTime());
			leagueInfo.setPortrait(previousLeagueInfo.getPortrait());
			leagueInfoAccess.updateLeagueInfo(leagueId, leagueInfo);
			response.sendRedirect("./home.jsp?league="+leagueId);
		} catch (SessionIdNotFound e) {
			printResult(response, FAILURE);
			return;
		} catch (SQLException e) {
			printResult(response, FAILURE);
			return;
		}
		printResult(response, SUCCESS);
	}
	
	private void printResult(HttpServletResponse response,
			boolean success) throws IOException {
		response.getWriter().println((success) ?
				SUCCESS_MESSAGE : FAILURE_MESSAGE);
	}

}
